package com.dynamic.mybatis.core.generator.helper;

import com.dynamic.mybatis.core.generator.InjectorHelper;
import com.dynamic.mybatis.core.metadata.MappedStatementMetaField;
import com.dynamic.mybatis.core.metadata.MappedStatementTable;

import java.util.Optional;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/14 16:20
 */
public class LogicDeleteHelper extends InjectorHelper {


    /**
     * 获取逻辑删除字段的 sql 脚本
     *
     * @param startWithAnd 是否以 and 开头
     * @param isWhere      是否需要的是逻辑删除值
     * @return sql 脚本
     */
    public static String getLogicDeleteSql(MappedStatementTable table, boolean startWithAnd, boolean isWhere) {
        Optional<MappedStatementMetaField> optionalField = getLogicDelete(table);
        if (optionalField.isPresent()) {
            String logicDeleteSql = formatLogicDeleteSql(optionalField.get(), isWhere);
            if (startWithAnd) {
                logicDeleteSql = " AND " + logicDeleteSql;
            }
            return logicDeleteSql;
        }
        return EMPTY;
    }


    /**
     * format logic delete SQL, can be overrided by subclass
     * github #1386
     *
     * @param isWhere true: logicDeleteValue, false: logicNotDeleteValue
     * @return sql
     */
    public static String formatLogicDeleteSql(MappedStatementMetaField logicDeleteField, boolean isWhere) {
        final String value = isWhere ? logicDeleteField.getLogicNotDeleteValue() : logicDeleteField.getLogicDeleteValue();
        if (isWhere) {
            if (NULL.equalsIgnoreCase(value)) {
                return logicDeleteField.getColumn() + " IS NULL";
            } else {
                return logicDeleteField.getColumn() + EQUALS + String.format(logicDeleteField.getJavaTypeClass().equals(String.class) ? "'%s'" : "%s", value);
            }
        }
        final String targetStr = logicDeleteField.getColumn() + EQUALS;
        if (NULL.equalsIgnoreCase(value)) {
            return targetStr + NULL;
        } else {
            return targetStr + String.format(logicDeleteField.getJavaTypeClass().equals(String.class) ? "'%s'" : "%s", value);
        }
    }


    /**
     * SQL 更新 set 语句
     *
     * @param table 表信息
     * @return sql set 片段
     */
    public static String sqlLogicSet(MappedStatementTable table) {
        return "SET " + LogicDeleteHelper.getLogicDeleteSql(table, false, false);
    }
}